package cn.memset.code.stream;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CollectExample {
    public static void main(String[] args) {
        groupEmployeesToMap1();
    }

    public static void collectToList() {
        Stream<String> stream = Stream.of("hello", "world", "I", "love", "you");
        List<String> list = stream.collect(Collectors.toList());
        System.out.println(list);
    }

    public static void collectToList1() {
        Stream<String> stream = Stream.of("hello", "world", "I", "love", "you");
        List<String> list = stream.collect(
                ArrayList::new,   // supplier 创建一个 ArrayList 实例
                ArrayList::add,   // accumulator 将一个 String 加入到 ArrayList 中
                ArrayList::addAll // combiner 将两个 ArrayList 合并成一个
        );

        System.out.println(list);
    }

    public static void collectEmployeeNamesToList() {
        List<Employee> employees = Utils.makeEmployees();
        List<String> names = employees.stream()
                .map(Employee::getName)
                .collect(Collectors.toList());

        // 如果要指定返回的List具体类型，譬如指定为 ArrayList
        ArrayList<String> arrayNames = employees.stream()
                .map(Employee::getName)
                .collect(Collectors.toCollection(ArrayList::new));

        System.out.println(arrayNames);
    }

    public static void collectEmployeeNamesToMap() {
        List<Employee> employees = Utils.makeEmployees();
        Map<String, Integer> nameScoreMap = employees.stream()
                .collect(Collectors.toMap(Employee::getName, Employee::getSalary));
        System.out.println(nameScoreMap);
    }

    public static void partitionEmployeesToMap() {
        List<Employee> employees = Utils.makeEmployees();
        Map<Boolean, List<Employee>> map = employees.stream()
                .collect(Collectors.partitioningBy(e -> e.getGender() == 1));
        System.out.println(map);
    }

    public static void groupEmployeesToMap() {
        List<Employee> employees = Utils.makeEmployees();
        Map<String, List<Employee>> map = employees.stream()
                .collect(Collectors.groupingBy(Employee::getDepartment));
        System.out.println(map);
    }

    public static void groupEmployeesToMap1() {
        List<Employee> employees = Utils.makeEmployees();

        // 使用增强版的 groupingBy
        Map<String, Integer> map = employees.stream()
                .collect(
                        // 上游收集器
                        Collectors.groupingBy(
                                Employee::getDepartment,
                                // 下游收集器 downstream collector
                                // 计算部门员工的总薪酬
                                Collectors.summingInt(Employee::getSalary)
                        )
                );

        System.out.println(map);
    }

}
